package template;

import java.sql.SQLException;
import java.util.Date;
import java.util.LinkedList;

import net.java.ao.DatabaseProvider;
import net.java.ao.EntityManager;

import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.PropertyModel;

/**
 * Page that adds a template border for layout.
 * 
 */
public class CreateEvent extends Restricted
{
	private String inputNameMessage = "";
	private String startDateInput = "";
	private String startTimeInput = "";
	private String endDateInput = "";
	private String endTimeInput = "";
	private String inputDescriptionMessage = "";
	private int selectedStartMonth;
	private int daysInStartMonth;
	private int daysInEndMonth;
	private int selectedEndMonth;
	private String selectedCalendar;
	private Calendar calendar;
	
    /**
     * Constructor
     */
	//nested private class of form to override onSubmit method
	private class CreateEventForm extends Form {
		private CreateEvent _createEvent;
		public CreateEventForm(String id, CreateEvent createEvent) {
			super(id);
			_createEvent = createEvent;
		}
		//onSubmit method, defines how to the page should react based on values
		//in the input fields
		public void onSubmit() {
			try {
				int created = _createEvent.createEvent();
				switch (created) {
				case 0:
					this.setResponsePage(ViewCalendars.class);
					break;
				case 1:
					this.setResponsePage(CreateEventNullDateError.class);
					break;
				case 2:
					this.setResponsePage(CreateEventEndDateError.class);
					break;
				case 3:
					this.setResponsePage(CreateEventNameError.class);
					break;
				default:
					this.setResponsePage(ViewCalendars.class);
					break;
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
    public CreateEvent()
    {
    	//propertymodels to reference in the html file
    	PropertyModel inputNameModel = new PropertyModel(this, "inputNameMessage");
    	PropertyModel startDateModel = new PropertyModel(this, "startDateInput");
    	PropertyModel startTimeModel = new PropertyModel(this, "startTimeInput");
    	PropertyModel endDateModel = new PropertyModel(this, "endDateInput");
    	PropertyModel endTimeModel = new PropertyModel(this, "endTimeInput");
    	PropertyModel inputDescriptionModel = new PropertyModel(this, "inputDescriptionMessage");
    	
    	//creation of the form private class
    	CreateEventForm form = new CreateEventForm("form", this);
    	
    	//adding each of the fields to the form
    	form.add(new TextArea("inputDescriptionArea", inputDescriptionModel));
    	form.add(new TextField("inputNameField", inputNameModel));
    	form.add(new TextField("startDate", startDateModel));
    	form.add(new TextField("startTime", startTimeModel));
    	form.add(new TextField("endDate", endDateModel));
    	form.add(new TextField("endTime", endTimeModel));
    	
    	//defining instance of EntityManager that handles database
    	EntityManager manager = new EntityManager(DatabaseProvider.getInstance(
				"jdbc:hsqldb:mem:basic-ao", null, null));
    	
    	//list of calendar names to be put into dropdown menu
    	LinkedList<String> calendarNames = new LinkedList<String>();
    	
    	//reference to user in current session
    	Person user = (Person)_session.getUser();
    	Calendar[] userCalendars;
    	
    	//uses the manager to find all calendars created by the user
		try {
			userCalendars = manager.find(Calendar.class, "creatorID = ?", user.getID());
	    	
			//puts names of Default Calendar and user-created Calendars into
			//the calendar names list
			for(int i=2;i<userCalendars.length;i++) {
	    		calendarNames.add(i-2, userCalendars[i].getName());
	    	}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//property model for the selected calendar name
		PropertyModel calendarModel = new PropertyModel(this, "selectedCalendar");
		
		//adds a dropdown menu to the form containing calendars available to place
		//the new event in
		form.add(new DropDownChoice("selectedCalendar", calendarModel, calendarNames));
		
		//add the form to the layout
    	_layout.add(form);
    }
    public int createEvent() throws SQLException {
    	
    	//if the name is null, direct user to error page saying the name was left blank
    	//or that the name already exists on that calendar
    	if(inputNameMessage == null)
    		return 3;
    	
    	//if any of the date/time fields are left blank, direct user to error page
    	//displaying this error
    	if(startDateInput == null || startTimeInput == null ||
    			endDateInput == null || endTimeInput == null)
    		return 1;
    	
    	//construct dates based on concatenations of the input fields for dates
    	Date startDate = new Date(startDateInput+","+startTimeInput+":");
    	Date endDate = new Date(endDateInput+","+endTimeInput+":");
    	
    	//if the end date is before the start date, direct user to appropriate error page
    	if(endDate.compareTo(startDate) < 0)
    		return 2;
    	
    	//assigning of variables
    	String name = inputNameMessage;
    	String description = inputDescriptionMessage;
    	
    	//make the default description "None" if nothing was entered
    	if(description == null)
    		description = "None";
    	
    	//if no calendar was selected, put the event on the Default Calendar
    	if(selectedCalendar == null)
    		selectedCalendar = "Default Calendar";
    	
    	//definition of instance of EntityManager that handles database
    	EntityManager manager = new EntityManager(DatabaseProvider.getInstance(
				"jdbc:hsqldb:mem:basic-ao", null, null));
    	
    	//reference to user in current session
    	Person user = (Person)_session.getUser();
    	
    	//find the calendar selected in the dropdown in the database based on creator
    	//and the name from the dropdown
    	Calendar[] calendar = manager.find(Calendar.class, "creatorID = ? AND name = ?", user.getID(), selectedCalendar);
    	
    	//retrieve all events on current calendar
    	Event[] calendarEvents = calendar[0].getEvents();
    	
    	//check that an event with same doesnt exist on selected calendar
    	//if so, direct to error page
    	for(int i=0;i<calendarEvents.length;i++) {
    		String eventName = calendarEvents[i].getName();
    		if(eventName.equalsIgnoreCase(name))
    			return 3;
    	}
    	
    	//creation of new event in Event table in database
    	Event event = manager.create(Event.class);
    	
    	//creation of new events-calendars relation in database
    	EventsToCalendars relation = manager.create(EventsToCalendars.class);
    	
    	//setting of attributes of event
    	event.setName(name);
    	event.setDescription(description);
    	event.setStartDate(startDate);
    	event.setEndDate(endDate);
    	event.save();
    	
    	//setting of calendarID to that selected and eventID to the new event
    	relation.setCalendar(calendar[0]);
    	relation.setEvent(event);
    	relation.save();
    	
    	//directing the user back to the ViewCalendars page
    	return 0;
    }
}